const https = require('https');
const SQLHelper = require('./SQLHelper')
const { formatTime } = require('./util')
///雪花算法生成id
const snowflake = require('./snowflake')




const db = require('./sequelize')


const multer = require('multer')
const storage = multer.diskStorage({
  destination: './uploads',
  filename: function (req, file, cb) {
    ///获取图片类型
    let fileType = file.originalname.split('.')
    fileType = fileType[fileType.length - 1]
    cb(null, snowflake() + '.' + fileType)
  }
})

const upload = multer({ storage: storage })

module.exports = function (app) {
  let tokens = {

  }
  ///登录拦截中间件
  function loginRouter(req, res, next) {
    if (req.method.toUpperCase() == 'OPTIONS') {
      next()
      return;
    }
    let token = req.headers.token
    if (token) {
      SQLHelper(`select * from session where id = ${token} and state = 1`).then(ret => {
        if (ret.length) {
          let session = ret[0]
          //2H
          if (new Date().getTime() - session.createTime < 2 * 60 * 60 * 1000) {
            req.session = {
              userId: session.userId,
              userName: session.userName
            }
            next()
          } else {
            res.status(400).send({ errorMsg: '登陆超时' })
          }

        } else {
          res.status(400).send({ errorMsg: '当前用户未登录' })
        }
      })
    } else {
      res.status(400).send({ errorMsg: '缺少token,请先进行登录' })
    }
  }




  ///对小程序的所有接口进行拦截,排除用户登录，此时没有token，也没有用户信息
  ///除了登录的所有接口都需要登录验证拦截
  app.use('/admin', loginRouter)




  ///文件上传
  app.post('/upload', upload.single('file'), (req, res) => {
    console.log(req.file)
    res.send(req.file)
  })

  ///管理后台登陆
  app.post('/login', (req, res, next) => {
    let userName = req.body.userName
    let passWord = req.body.passWord
    if (userName && passWord) {
      SQLHelper(`
          select * from user where userName = '${userName}'
      `).then(users => {
        if (users.length) {///正常登录
          let user = users[0]
          if (passWord == user.passWord) {
            let token = snowflake()
            ///缓存到tokens到session表
            SQLHelper(`
  INSERT INTO session(id,userId,userName,inTime,createTime,platform)
  VALUES(${token},'${user._id}','${user.nickName}','${formatTime(new Date())}',${new Date().getTime()},'admin')
  `).then(ret => {
              res.send({
                nickName: user.nickName,
                token,
                avatarUrl: user.photo,
                _id: user._id
              })
            })
          } else {
            res.send({ errorMsg: '密码错误' })
          }
        }
      })
    } else {
      res.send({ errorMsg: '用户名和密码不能为空' })
    }
  })

  //退出登录
  app.get('/admin/logout', (req, res) => {
    SQLHelper(`
        update session set outTime = '${formatTime(new Date())}',state = 0 
        where id = '${req.headers.token}'
    `).then(ret => {
      res.send({ msg: '退出登陆成功' })
    })
  })

  //修改密码
  app.post('/admin/changePassWord', (req, res) => {
    let userId = req.session.userId
    let passWord = req.body.passWord
    let newPassWord = req.body.newPassWord
    if (passWord && newPassWord) {
      //通过userId和密码查询用户
      SQLHelper(`select passWord from user where _id = ${userId}`).then(users => {
        let user = users[0]
        //比对原密码
        if (user.passWord == passWord) {
          //修改密码
          SQLHelper(`update user set passWord = '${newPassWord}' where _id = ${userId}`).then(ret => {
            res.send({ msg: '修改密码成功' })
          })
        } else {
          res.send({ errorMsg: '原密码错误' })
        }
      })
    } else {
      res.send({ errorMsg: '原密码和新密码不能为空' })
    }
  })


  ///分页获取首页首页项目列表
  ///pageSize 每页大小，默认10
  //pageNum 当前页 默认1
  ///type 类型 非必填 banner, 轮播图 category, 分类 recomend,为你推荐  不填搜索全部
  app.get('/admin/index', (req, res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let title = req.query.title
    let type = req.query.type
    let whereSql = 'from index_region where state = 1'
    ///按类型查询
    if (type) whereSql += ` and type = '${type}'`
    ///按标题关键字搜索
    if (title) whereSql += ` and title like "%${title}%"`
    SQLHelper(`
          select count(*) as total ${whereSql};
          select * ${whereSql}
          limit ${pageSize} offset ${offset}
      `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })




  ///新增首页项目
  ///img  图片地址必填
  ///url  链接地址非必填
  ///title 标题 轮播图不填，其他必填
  ///status  是否启用非必填 1 表示启用 0
  ///type 类型 非必填 banner(默认), 轮播图 category, 分类 recomend,为你推荐
  app.post('/admin/index', (req, res) => {
    let img = req.body.img, url = req.body.url, status = req.body.status,
      type = req.body.type || 'banner', title = req.body.title
    if (type != 'banner' && !title) {
      res.send({ errorMsg: '标题不能为空' })
      return
    }
    if (status != 1) status = 0  //默认启用
    if (img) {
      let createTime = new Date().getTime()
      SQLHelper(`
       INSERT INTO index_region(title,img,url,status,state,createTime,unitId,type)
       VALUES('${title}','${img}','${url}','${status}',1,${createTime},'juzao','${type}')
  `).then(ret => {
        // console.log(98786,ret)
        res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: '新增数据失败' })
      })

    } else {
      res.send({ errorMsg: '传入参数错误' })
    }

  })



  ///修改首页项目
  ///indexId 主码id必填
  app.put('/admin/index', (req, res) => {
    if (req.body.indexId) {
      ///需要修改的项
      let updateTime = new Date().getTime()
      let updateKey = ['img', 'url', 'title', 'status']
      let updateValues = [`updateTime=${updateTime}`]
      for (let i = 0; i < updateKey.length; i++) {
        let key = updateKey[i], value = req.body[key]
        if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些需要修改
      }
      SQLHelper(`UPDATE index_region set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  ///删除地址:逻辑删除
  ///addressId  主码_id必填
  app.delete('/admin/index', (req, res) => {
    let indexId = req.query.indexId
    if (indexId) {
      SQLHelper(`
        UPDATE index_region
        set state = 0
        WHERE _id = ${indexId}
  `).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '请传入参数错误' })
    }
  })











  // 品牌管理

  //分页获取品牌列表
  ///pageSize 每页大小，默认10
  //pageNum 当前页 默认1
  app.get('/admin/brand', (req, res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let name = req.query.name
    let img = req.query.img
    let whereSql = 'from brand where state = 1'
    ///按品牌的名称查询
    if (name) whereSql += ` and name = '${name}'`
    SQLHelper(`
          select count(*) as total ${whereSql};
          select * ${whereSql}
          limit ${pageSize} offset ${offset}
      `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })



  ///新增品牌
  ///img  图片地址必填
  ///url  链接地址非必填
  ///title 标题 轮播图不填，其他必填
  ///status  是否启用非必填 1 表示启用 0
  ///type 类型 非必填 banner(默认), 轮播图 category, 分类 recomend,为你推荐
  app.post('/admin/brand', (req, res) => {
    let img = req.body.img, name = req.body.name
    if (img) {
      let createTime = new Date().getTime()
      SQLHelper(`
       INSERT INTO brand(img,name,state,createTime,unitId)
       VALUES ('${img}','${name}',1,${createTime},'juzao')
  `).then(ret => {
        res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: '新增数据失败' })
      })

    } else {
      res.send({ errorMsg: '传入参数错误' })
    }

  })



  ///修改首页项目
  ///indexId 主码id必填
  app.put('/admin/brand', (req, res) => {
    if (req.body.indexId) {
      ///需要修改的项
      let updateTime = new Date().getTime()
      let updateKey = ['img', 'name']
      let updateValues = [`updateTime=${updateTime}`]
      for (let i = 0; i < updateKey.length; i++) {
        let key = updateKey[i], value = req.body[key]
        if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些需要修改
      }
      SQLHelper(`UPDATE brand set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  ///删除地址:逻辑删除
  ///addressId  主码_id必填
  app.delete('/admin/brand', (req, res) => {
    let indexId = req.query.indexId
    if (indexId) {
      SQLHelper(`
        UPDATE brand
        set state = 0
        WHERE _id = ${indexId}
  `).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '请传入参数错误' })
    }
  })






  ///单品管理

  //分页获取单品管理列表
  ///pageSize 每页大小，默认10
  //pageNum 当前页 默认1
  app.get('/admin/good', (req, res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let productName = req.query.productName 
    let whereSql = 'from sku where state = 1'
    ///按商品的关键字查询
    if (productName) whereSql += ` and productName like '%${productName}%'`
    SQLHelper(`
          select count(*) as total ${whereSql};
          select * ${whereSql}
          limit ${pageSize} offset ${offset}
      `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })




  ///新增单品
  /// skuId 必填
  app.post('/admin/good', (req, res) => {
    let imgs = req.body.imgs, skuId = req.body.skuId, salePrice = req.body.salePrice, originalPrice = req.body.originalPrice
    let productName = req.body.productName, props = req.body.props, productId = req.body.productId
    if (skuId) {
      let createTime = new Date().getTime()
      SQLHelper(`
       INSERT INTO sku(imgs,skuId,salePrice,productName,originalPrice,state,unitId,props,productId)
       VALUES('${imgs}','${skuId}','${salePrice}','${productName}','${originalPrice}',1,'juzao','${props}','${productId}')
  `).then(ret => {
        res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: '新增数据失败' })
      })

    } else {
      res.send({ errorMsg: '传入参数错误' })
    }

  })



  ///修改首页项目
  ///indexId 主码id必填
  app.put('/admin/good', (req, res) => {
    if (req.body.indexId) {
      ///需要修改的项
      let updateTime = new Date().getTime()
      let updateKey = ['imgs', 'skuId', 'salePrice', 'productName', 'originalPrice', 'props']
      let updateValues = [`updateTime=${updateTime}`]
      for (let i = 0; i < updateKey.length; i++) {
        let key = updateKey[i], value = req.body[key]
        if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些需要修改
      }
      SQLHelper(`UPDATE sku set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  ///删除地址:逻辑删除
  ///addressId  主码_id必填
  app.delete('/admin/good', (req, res) => {
    let indexId = req.query.indexId
    if (indexId) {
      SQLHelper(`
        UPDATE sku
        set state = 0
        WHERE _id = ${indexId}
  `).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '请传入参数错误' })
    }
  })







  ///商品管理



  //分页获取商品管理列表
  ///pageSize 每页大小，默认10
  //pageNum 当前页 默认1
  ///type 类型 非必填 banner, 轮播图 category, 分类 recomend,为你推荐  不填搜索全部
  app.get('/admin/goods', (req, res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let name = req.query.name
    let imgs = req.query.imgs
    let sales = req.query.sales
    let brandId = req.query.brandId
    let whereSql = 'from product where state = 1'
    ///按商品的名称查询
    if (name) whereSql += ` and name like '%${name}%'`
    SQLHelper(`
          select count(*) as total ${whereSql};
          select * ${whereSql}
          limit ${pageSize} offset ${offset}
      `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })


  ///新增商品管理
  //img 图片地址 必填
  //status 是否上架 非必填 1上架，0未上架
  app.post('/admin/goods', (req, res) => {
    let imgs = req.body.imgs, name = req.body.name, status = req.body.status,brandId = req.body.brandId,sales = req.body.sales
    if (status != 1) status = 0  //默认启用
    if (imgs) {
      let createTime = new Date().getTime()
      SQLHelper(`
       INSERT INTO product(name,imgs,brandId,status,state,createTime,unitId,sales)
       VALUES('${name}','${imgs}','${brandId}','${status}',1,${createTime},'juzao','${sales}')
  `).then(ret => {
        res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: '新增数据失败' })
      })

    } else {
      res.send({ errorMsg: '传入参数错误' })
    }

  })


  ///修改商品管理
  ///indexId 主码id必填
  app.put('/admin/goods', (req, res) => {
    if (req.body.indexId) {
      ///需要修改的项
      let updateTime = new Date().getTime()
      let updateKey = ['imgs', 'name', 'sales','status','brandId']
      let updateValues = [`updateTime=${updateTime}`]
      for (let i = 0; i < updateKey.length; i++) {
        let key = updateKey[i], value = req.body[key]
        if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些需要修改
      }
      SQLHelper(`UPDATE product set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  ///删除地址:逻辑删除
  ///addressId  主码_id必填
  app.delete('/admin/goods', (req, res) => {
    let indexId = req.query.indexId
    if (indexId) {
      SQLHelper(`
        UPDATE product
        set state = 0
        WHERE _id = ${indexId}
  `).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '请传入参数错误' })
    }
  })






  // 新闻管理

  //分页获取新闻列表
  ///pageSize 每页大小，默认10
  //pageNum 当前页 默认1
  ///type 类型 非必填 banner, 轮播图 category, 分类 recomend,为你推荐  不填搜索全部
  app.get('/admin/news', (req, res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let title = req.query.title
    let digest = req.query.digest
    let img = req.query.img
    let whereSql = 'from article where state = 1'
    // ///按新闻的标题查询
    if (title) whereSql += ` and title like '%${title}%'`
    SQLHelper(`
          select count(*) as total ${whereSql};
          select * ${whereSql}
          limit ${pageSize} offset ${offset}
      `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })



  ///新增新闻条
  ///img  图片地址非必填
  ///url  链接地址非必填
  ///标题、摘要必填。其他的非必填
  ///status  是否启用非必填 1 表示启用 0
  app.post('/admin/news', (req, res) => {
    let img = req.body.img, digest = req.body.digest, status = req.body.status
    let type = req.body.type || 'news', title = req.body.title
    if (type != 'news' && !title) {
      res.send({ errorMsg: '标题不能为空' })
      return
    }
    if (status != 1) status = 0  //默认启用
    if (title) {
      let createTime = new Date().getTime()
      SQLHelper(`
       INSERT INTO article(img,title,digest,status,state,createTime,unitId,type)
       VALUES('${img}','${title}','${digest}','${status}',1,${createTime},'juzao','${type}')
  `).then(ret => {
        res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: '新增数据失败' })
      })

    } else {
      res.send({ errorMsg: '传入参数错误' })
    }

  })



  ///修改新闻
  ///indexId 主码id必填
  app.put('/admin/news', (req, res) => {
    if (req.body.indexId) {
      ///需要修改的项
      let updateTime = new Date().getTime()
      let updateKey = ['img', 'title', 'digest', 'status']
      let updateValues = [`updateTime=${updateTime}`]
      for (let i = 0; i < updateKey.length; i++) {
        let key = updateKey[i], value = req.body[key]
        if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些需要修改
      }
      SQLHelper(`UPDATE article set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  ///删除新闻条:逻辑删除
  ///addressId  主码_id必填
  app.delete('/admin/news', (req, res) => {
    let indexId = req.query.indexId
    if (indexId) {
      SQLHelper(`
        UPDATE article
        set state = 0
        WHERE _id = ${indexId}
  `).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '请传入参数错误' })
    }
  })











}

